package com.iss.supermarket.util.MessageWindow;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class MsgWin extends JFrame{
    //单例模式
    private static MsgWin msgWin;
    //定义组件
    private JLabel msgLabel;
    private String msg;

    public MsgWin(String msg){
        super("提示");

        this.msg = msg+"！";
        InitAssembly();
        InitUI();
    }

    public void InitUI(){
        Container container = getContentPane();
        Box verticalBox = Box.createVerticalBox();

        JPanel jPanel1 = new JPanel();
        jPanel1.add(msgLabel);
        verticalBox.add(jPanel1);

        container.add(verticalBox);
        Dimension dimension = new Dimension();
        dimension = msgLabel.getPreferredSize();
        //根据提示信息设置窗口大小
        setSize(Math.max((dimension.width + dimension.width / 2), 250),100);
        setVisible(true);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setComponentInCenter(this);
    }

    private void InitAssembly(){
        msgLabel = new JLabel(this.msg);
        msgLabel.setPreferredSize(new Dimension((20*this.msg.length()),25));
        msgLabel.setFont(new Font("微软雅黑",Font.PLAIN,16));

        //设置回车键关闭窗口
        this.addKeyListener(new KeyListener() {
            @Override
            public void keyPressed(KeyEvent e) {
                if(e.getKeyCode() == KeyEvent.VK_ENTER){
                    dispose();
                }
            }
            @Override
            public void keyTyped(KeyEvent e) {

            }
            @Override
            public void keyReleased(KeyEvent e) {
            }
        });
    }

    private void setComponentInCenter(Component component){
        Dimension UISIZAE = component.getSize();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        if (UISIZAE.height > screenSize.height)
            UISIZAE.height = screenSize.height;
        if (UISIZAE.width > screenSize.width)
            UISIZAE.width = screenSize.width;
        component.setLocation((screenSize.width - UISIZAE.width) / 2, (screenSize.height - UISIZAE.height) / 2);
    }

    public static synchronized MsgWin getMsgWin(String msg){
        if(msgWin == null){
            msgWin = new MsgWin(msg);
        }
        return msgWin;
    }
}
